/**  定义电影院相关的接口 */
const express = require("express");
const router = express.Router();
const Joi = require("joi");
const Response = require("../utils/Response.js");

// 引入mysql连接池
const pool = require("../utils/db.js");

router.post("/agent/del", (req, resp) => {
  let { id } = req.body;
  // 执行删除业务
  let sql = "delete from mac_agent where id = ?";
  pool.query(sql, [id], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    resp.send(Response.ok());
  });
});

router.get("/agent/query", (req, resp) => {
  let { id } = req.query;

  // 执行查询业务
  let sql = "select * from mac_agent where id=?";
  pool.query(sql, [id], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    if (result && result.length == 0) {
      // 没查到
      resp.send(Response.ok(null));
    } else {
      resp.send(Response.ok(result[0]));
    }
  });
});

router.get("/agents", (req, resp) => {
  let sql = "select * from mac_agent";
  pool.query(sql, (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    resp.send(Response.ok(result));
  });
});

router.post("/agent/add", (req, resp) => {
  let {
    name,
    address,
    province,
    city,
    district,
    longitude,
    latitude,
    id,
    phone,
    email,
  } = req.body; // post请求参数在req.body中

  let sql = `insert into mac_agent (
    name,
    address,
    province,
    city,
    district,
    longitude,
    latitude,
    id,
    phone,
    email) values (?,?,?,?,?,?,?,?,?,?)`;
  pool.query(
    sql,
    [
      name,
      address,
      province,
      city,
      district,
      longitude,
      latitude,
      id,
      phone,
      email,
    ],
    (error, result) => {
      if (error) {
        resp.send(Response.error(500, error));
        throw error;
      }
      resp.send(Response.ok());
    }
  );
});

router.post("/agent/put", (req, resp) => {
  let {
    name,
    address,
    province,
    city,
    district,
    longitude,
    latitude,
    id,
    phone,
    email,
  } = req.body; // post请求参数在req.body中
  let sql =
    "update mac_agent set name=?,address=?,province=?,city=?,phone=?,email=?,district=?,longitude=?,latitude=? where id=?";
  pool.query(
    sql,
    [
      name,
      address,
      province,
      city,
      district,
      longitude,
      latitude,
      id,
      phone,
      email,
    ],
    (error, result) => {
      if (result.changedRows === 0) {
        resp.send({
          code: 400,
          msg: "修改失败",
        });
      } else {
        resp.send({
          code: 200,
          msg: "修改成功",
          data: result,
        });
      }
    }
  );
});

// 将router对象导出
module.exports = router;
